<script lang="ts" setup>
import {
  ElMessageBox,
  ElDialog,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElRadioGroup,
  ElRadio,
  ElMessage,
  ElSelect,
  ElOption,
  ElTreeSelect,
} from "element-plus";
import { nextTick, reactive, ref } from "vue";
import { add, edit, getUserById, resetUserPassword } from "#/api/sys/user";
import { getOrganizationsByUserId } from "#/api/sys/organization";
import { getStartingRole } from "#/api/sys/role";

const dialogVisible = ref(false);
const title = ref("添加账号");

const spaceInput = (field: string, value: string) => {
  // 过滤空格
  ruleForm[field] = value.replace(/\s+/g, "");
};

const useForm = () => {
  const formRef = ref();
  const reset = async () => {
    await nextTick();
    formRef.value?.resetFields();
  };
  return { formRef, reset };
};
const { formRef: ruleFormRef, reset } = useForm();
const addDialog = () => {
  dialogVisible.value = true;
  title.value = "添加账号";
  reset();
  getTableData();
  getRoleData();
};

const editDialog = (obj) => {
  dialogVisible.value = true;
  title.value = "编辑账号";
  ruleForm.id = obj.id;
  getDetail(obj.id);
  getTableData();
  getRoleData();
};

defineExpose({ addDialog, editDialog });
const emit = defineEmits(["search"]);

const getDetail = async (id) => {
  const params = {
    id: id,
  };
  const { data } = await getUserById(params);
  ruleForm.userName = data.userName;
  ruleForm.realName = data.realName;
  ruleForm.status = data.status + "";
  ruleForm.phone = data.mobile;
  ruleForm.password = data.password;
  ruleForm.organizationId = data.organizationId;
  ruleForm.roleId = data.roleId;
};

const ruleForm = reactive<RuleForm>({
  id: "",
  userName: "",
  realName: "",
  password: "FEISUAN888",
  status: "1",
  role: "",
  chargeName: "",
  organizationId: "",
  roleId: "",
});

const rules = reactive({
  userName: [
    { required: true, message: "请输入账号", trigger: "blur" },
    {
      min: 6,
      max: 18,
      message: "请输入6-18位字符，允许英文字母、数字或特殊符号",
      trigger: "blur",
    },
  ],
  realName: [
    { required: true, message: "请输入名称", trigger: "blur" },
    {
      min: 2,
      max: 18,
      message: "请输入2-18位字符，允许英文字母、汉字、数字",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 1, max: 20, message: "请输入最多20字", trigger: "blur" },
  ],
  organizationId: [
    { required: true, message: "请选择所属组织", trigger: "change" },
  ],
  roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  chargeName: [{ min: 1, max: 20, message: "请输入最多20字", trigger: "blur" }],
});
const treeData = ref([]);
const defaultProps = {
  children: "children",
  label: "organizationName",
};
const roleOptions = ref([]);

const loading = ref(false);

const addForm = () => handleSubmit(false);
const editForm = () => handleSubmit(true);

const buildFormParams = (isEdit: boolean) => ({
  ...(isEdit && { id: ruleForm.id }),
  userName: ruleForm.userName,
  status: ruleForm.status,
  realName: ruleForm.realName,
  mobile: ruleForm.phone,
  password: ruleForm.password,
  organizationId: ruleForm.organizationId,
  roleId: ruleForm.roleId,
});

const handleApiResponse = (isEdit: boolean) => {
  ElMessage.success(isEdit ? "修改成功" : "添加成功");
  emit("search");
  dialogVisible.value = false;
};

const submitForm = async (isEdit = false) => {
  if (loading.value) return;

  try {
    loading.value = true;
    await ruleFormRef.value?.validate();

    const params = buildFormParams(isEdit);
    const { code, msg } = isEdit ? await edit(params) : await add(params);

    if (code === 200) handleApiResponse(isEdit);
    else ElMessage.error("操作失败," + msg);
  } catch (error) {
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

const resetForm = (formEl) => {
  if (!formEl) return;
  ruleFormRef.value.resetFields();
  dialogVisible.value = false;
};

const handleClose = (done: () => void) => {
  dialogVisible.value = false;
};

const getTableData = async () => {
  const { data } = await getOrganizationsByUserId();
  treeData.value = data;
};

const getRoleData = async () => {
  const { data } = await getStartingRole();
  roleOptions.value = data;
};

const resetPassword = async () => {
  try {
    await ElMessageBox.confirm("确定要重置该用户的密码吗？", "提示", {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose: async (action, instance, done) => {
        if (action === "confirm") {
          instance.confirmButtonLoading = true;
          try {
            await resetUserPassword(ruleForm.id);
            done();
          } catch (error) {
            instance.confirmButtonLoading = false;
          }
        } else {
          done();
        }
      },
    });
    ElMessage.success("重置密码成功");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`操作失败: ${error.message || "未知错误"}`);
      console.error("重置密码失败:", error);
    }
  }
};
</script>

<template>
  <div class="page">
    <ElDialog
      v-model="dialogVisible"
      :title="title"
      width="600"
      :before-close="handleClose"
    >
      <div>
        <ElForm
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
        >
          <ElFormItem label="账号：" prop="userName">
            <ElInput
              v-model="ruleForm.userName"
              placeholder="请输入账号"
              style="width: 420px"
              @input="(value) => spaceInput('userName', value)"
            />
          </ElFormItem>
          <ElFormItem label="姓名：" prop="realName">
            <ElInput
              v-model="ruleForm.realName"
              placeholder="请输入姓名"
              style="width: 420px"
              @input="(value) => spaceInput('realName', value)"
            />
          </ElFormItem>
          <ElFormItem label="手机号码：" prop="phone">
            <ElInput
              v-model="ruleForm.phone"
              placeholder="请输入手机号码"
              style="width: 420px"
              @input="(value) => spaceInput('phone', value)"
            />
          </ElFormItem>
          <ElFormItem label="密码：" prop="password" v-if="title == '添加账号'">
            <ElInput
              v-model="ruleForm.password"
              placeholder="请输入密码"
              style="width: 420px"
              @input="(value) => spaceInput('password', value)"
            />
          </ElFormItem>
          <ElFormItem label="负责人：" prop="chargeName">
            <ElInput
              v-model="ruleForm.chargeName"
              placeholder="请输入负责人"
              style="width: 420px"
              @input="(value) => spaceInput('chargeName', value)"
            />
          </ElFormItem>
          <ElFormItem label="所属组织：" prop="organizationId">
            <ElTreeSelect
              v-model="ruleForm.organizationId"
              :data="treeData"
              :props="{
                children: 'children',
                label: 'organizationName',
                disabled: (data) => data.status === false || data.disabled == 1,
              }"
              node-key="id"
              :render-after-expand="false"
              check-strictly
              placeholder="请选择所属组织"
              style="width: 420px"
            />
          </ElFormItem>
          <ElFormItem label="角色：" prop="roleId">
            <ElSelect
              v-model="ruleForm.roleId"
              placeholder="请选择角色"
              style="width: 420px"
            >
              <ElOption
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="状态：" prop="status">
            <ElRadioGroup v-model="ruleForm.status" placeholder="请选择状态">
              <ElRadio value="1">启用</ElRadio>
              <ElRadio value="2">禁用</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
        </ElForm>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ElButton
            v-if="title == '编辑账号'"
            type="primary"
            style="float: left"
            @click="resetPassword()"
          >
            重置密码
          </ElButton>
          <ElButton @click="resetForm(ruleFormRef)">取消</ElButton>
          <ElButton
            type="primary"
            @click="() => submitForm(title !== '添加账号')"
            :loading="loading"
          >
            确定
          </ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>
